package scope

import "gorm.io/gorm"

type JoinType int

const (
	JoinTypeInner JoinType = iota // 内联
	JoinTypeLeft                  // 左联
	JoinTypeRight                 // 右联
	JoinTypeFull                  // 全联
)

func WithJoin(table any, alias string, joinType JoinType, on string) Join {
	return Join{
		Table:    table,
		Alias:    alias,
		JoinType: joinType,
		On:       on,
	}
}

type Join struct {
	Table    any
	Alias    string
	JoinType JoinType
	On       string
}

func (j Join) MakeScope() Scope {

	joinCmd := ""
	switch j.JoinType {
	case JoinTypeInner:
		joinCmd = "INNER JOIN (?)"
	case JoinTypeLeft:
		joinCmd = "LEFT JOIN (?)"
	case JoinTypeRight:
		joinCmd = "RIGHT JOIN (?)"
	case JoinTypeFull:
		joinCmd = "FULL JOIN (?)"
	default:
		joinCmd = "INNER JOIN (?)"
	}

	if j.Alias != "" {
		joinCmd = joinCmd + " AS " + j.Alias
	}

	if j.On != "" {
		joinCmd = joinCmd + " ON " + j.On
	}

	return func(d *gorm.DB) *gorm.DB {
		return d.Joins(joinCmd, j.Table)
	}
}
